/*
 * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */

package jsr203.sun.nio.fs;

import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import jsr203.nio.channels.SeekableByteChannel;
import jsr203.nio.file.AtomicMoveNotSupportedException;
import jsr203.nio.file.ClosedDirectoryStreamException;
import jsr203.nio.file.DirectoryEntry;
import jsr203.nio.file.DirectoryNotEmptyException;
import jsr203.nio.file.DirectoryStream;
import jsr203.nio.file.FileRef;
import jsr203.nio.file.NotDirectoryException;
import jsr203.nio.file.OpenOption;
import jsr203.nio.file.Path;
import jsr203.nio.file.ProviderMismatchException;
import jsr203.nio.file.SecureDirectoryStream;
import jsr203.nio.file.attribute.Attribute;
import jsr203.nio.file.attribute.BasicFileAttributeView;
import jsr203.nio.file.attribute.BasicFileAttributes;
import jsr203.nio.file.attribute.FileAttributeView;
import jsr203.nio.file.attribute.FileOwnerAttributeView;
import jsr203.nio.file.attribute.PosixFileAttributeView;
import jsr203.nio.file.attribute.PosixFileAttributes;
import jsr203.nio.file.attribute.PosixFilePermission;
import jsr203.nio.file.attribute.UserPrincipal;
import static jsr203.sun.nio.fs.UnixConstants.AT_REMOVEDIR;
import static jsr203.sun.nio.fs.UnixConstants.EEXIST;
import static jsr203.sun.nio.fs.UnixConstants.ENOTEMPTY;
import static jsr203.sun.nio.fs.UnixConstants.EXDEV;
import static jsr203.sun.nio.fs.UnixConstants.O_NOFOLLOW;
import static jsr203.sun.nio.fs.UnixConstants.O_RDONLY;
import static jsr203.sun.nio.fs.UnixNativeDispatcher.dup;
import static jsr203.sun.nio.fs.UnixNativeDispatcher.fchmod;
import static jsr203.sun.nio.fs.UnixNativeDispatcher.fchown;
import static jsr203.sun.nio.fs.UnixNativeDispatcher.fdopendir;
import static jsr203.sun.nio.fs.UnixNativeDispatcher.futimes;
import static jsr203.sun.nio.fs.UnixNativeDispatcher.openat;
import static jsr203.sun.nio.fs.UnixNativeDispatcher.renameat;
import static jsr203.sun.nio.fs.UnixNativeDispatcher.unlinkat;

/**
 * Unix implementation of SecureDirectoryStream.
 */

class UnixSecureDirectoryStream
    extends SecureDirectoryStream
{
    private final UnixDirectoryStream ds;
    private final int dfd;

    UnixSecureDirectoryStream(UnixPath dir,
                              long dp,
                              int dfd,
                              DirectoryStream.Filter filter)
    {
        this.ds = new UnixDirectoryStream(dir, dp, filter);
        this.dfd = dfd;
    }

    @Override
    public void close()
        throws IOException
    {
        ds.writeLock().lock();
        try {
            if (ds.closeImpl()) {
                UnixNativeDispatcher.close(dfd);
            }
        } finally {
            ds.writeLock().unlock();
        }
    }

    @Override
    public Iterator<DirectoryEntry> iterator() {
        return ds.iterator(this);
    }

    private UnixPath getName(Path obj) {
        if (obj == null)
            throw new NullPointerException();
        if (!(obj instanceof UnixPath))
            throw new ProviderMismatchException();
        return (UnixPath)obj;
    }

    /**
     * Opens sub-directory in this directory
     */
    @Override
    public SecureDirectoryStream newDirectoryStream(Path obj,
                                                    boolean followLinks,
                                                    DirectoryStream.Filter filter)
        throws IOException
    {
        UnixPath file = getName(obj);
        UnixPath child = ds.directory().resolve(file);

        // permission check using name resolved against original path of directory
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            child.checkRead();
        }

        ds.readLock().lock();
        try {
            if (!ds.isOpen())
                throw new ClosedDirectoryStreamException();

            // open directory and create new secure directory stream
            int newdfd1 = -1;
            int newdfd2 = -1;
            long ptr = 0L;
            try {
                int flags = O_RDONLY;
                if (!followLinks)
                    flags |= O_NOFOLLOW;
                newdfd1 = openat(dfd, file.asByteArray(), flags , 0);
                newdfd2 = dup(newdfd1);
                ptr = fdopendir(newdfd1);
            } catch (UnixException x) {
                if (newdfd1 != -1)
                    UnixNativeDispatcher.close(newdfd1);
                if (newdfd2 != -1)
                    UnixNativeDispatcher.close(newdfd2);
                if (x.errno() == UnixConstants.ENOTDIR)
                    throw new NotDirectoryException(file.toString());
                x.rethrowAsIOException(file);
            }
            return new UnixSecureDirectoryStream(child, ptr, newdfd2, filter);
        } finally {
            ds.readLock().unlock();
        }
    }

    /**
     * Opens file in this directory
     */
    @Override
    public SeekableByteChannel newSeekableByteChannel(Path obj,
                                                      Set<? extends OpenOption> options,
                                                      Attribute<?>... attrs)
        throws IOException
    {
        UnixPath file = getName(obj);

        int mode = UnixFileModeAttribute
            .toUnixMode(UnixFileModeAttribute.ALL_READWRITE, attrs);

        // path for permission check
        String pathToCheck = ds.directory().resolve(file).getPathForPermissionCheck();

        ds.readLock().lock();
        try {
            if (!ds.isOpen())
                throw new ClosedDirectoryStreamException();
            try {
                return UnixChannelFactory
                    .newFileChannel(dfd,
                                    file.asByteArray(),
                                    pathToCheck,
                                    options,
                                    mode);
            } catch (UnixException x) {
                x.rethrowAsIOException(file);
                return null; // keep compiler happy
            }
        } finally {
            ds.readLock().unlock();
        }
    }

    /**
     * Deletes file in this directory
     */
    @Override
    public void delete(Path obj) throws IOException {
        UnixPath file = getName(obj);

        // permission check using name resolved against original path of directory
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkDelete(ds.directory().resolve(file).getPathForPermissionCheck());
        }

        ds.readLock().lock();
        try {
            if (!ds.isOpen())
                throw new ClosedDirectoryStreamException();

            // need file attribute to know if file is directory
            UnixFileAttributes attrs = null;
            try {
                attrs = UnixFileAttributes.get(dfd, file.asByteArray(), false);
            } catch (UnixException x) {
                x.rethrowAsIOException(file);
            }
            // there is a race here. If a file is replaced by a direcory or
            // a direcory replaced by a file then the following will either
            // fail or unlink a directory (if that is allowed).
            try {
                int flag = (attrs.isDirectory()) ? AT_REMOVEDIR : 0;
                unlinkat(dfd, file.asByteArray(), flag);
            } catch (UnixException x) {
                if (attrs.isDirectory()) {
                    if (x.errno() == EEXIST || x.errno() == ENOTEMPTY) {
                        throw new DirectoryNotEmptyException(null);
                    }
                }
                x.rethrowAsIOException(file);
            }
        } finally {
            ds.readLock().unlock();
        }
    }


    /**
     * Rename/move file in this directory to another (open) directory
     */
    @Override
    public void move(Path fromObj, SecureDirectoryStream dir, Path toObj)
        throws IOException
    {
        UnixPath from = getName(fromObj);
        UnixPath to = getName(toObj);
        if (dir == null)
            throw new NullPointerException();
        if (!(dir instanceof UnixSecureDirectoryStream))
            throw new ProviderMismatchException();
        UnixSecureDirectoryStream that = (UnixSecureDirectoryStream)dir;

        // permission check
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            this.ds.directory().resolve(from).checkWrite();
            that.ds.directory().resolve(to).checkWrite();
        }

        // lock ordering doesn't matter
        this.ds.readLock().lock();
        try {
            that.ds.readLock().lock();
            try {
                if (!this.ds.isOpen() || !that.ds.isOpen())
                    throw new ClosedDirectoryStreamException();
                try {
                    renameat(this.dfd, from.asByteArray(), that.dfd, to.asByteArray());
                } catch (UnixException x) {
                    if (x.errno() == EXDEV) {
                        throw new AtomicMoveNotSupportedException(
                            from.toString(), to.toString(), x.errorString());
                    }
                    x.rethrowAsIOException(from, to);
                }
            } finally {
                that.ds.readLock().unlock();
            }
        } finally {
            this.ds.readLock().unlock();
        }
    }

    @SuppressWarnings("unchecked")
    private <V extends FileAttributeView> V newFileAttributeViewImpl(UnixPath file,
                                                                     Class<V> type,
                                                                     boolean followLinks)
    {
        if (type == null)
            throw new NullPointerException();
        Class<?> c = type;
        if (c == BasicFileAttributeView.class) {
            BasicFileAttributeView view = UnixFileAttributeView.createBasicView();
            return (V) new BasicForwardingFileAttributeView(file, view, followLinks);
        }
        if (c == PosixFileAttributeView.class || c == FileOwnerAttributeView.class) {
            PosixFileAttributeView view = UnixFileAttributeView.createPosixView();
            return (V) new PosixForwardingFileAttributeView(file, view, followLinks);
        }
        // TBD - should also support AclFileAttributeView
        return (V) null;
    }

    /**
     * Returns file attribute view is initially bound to this directory
     */
    @Override
    public <V extends FileAttributeView> V newFileAttributeView(Class<V> type) {
        return newFileAttributeViewImpl(null, type, false);
    }

    /**
     * Returns file attribute view is initially bound to dfd/filename.
     */
    @Override
    public <V extends FileAttributeView> V newFileAttributeView(Path obj,
                                                                Class<V> type,
                                                                boolean followLinks)
    {
        UnixPath file = getName(obj);
        return newFileAttributeViewImpl(file, type, followLinks);
    }

    /**
     * BasicForwardingFileAttributeView that works initially on the dfd/name
     * pair. When the bind method is used to bind the view to a another file
     * then it forwards.
     */
    private class BasicForwardingFileAttributeView
        implements BasicFileAttributeView
    {
        final UnixPath file;
        final BasicFileAttributeView forwardee;
        final boolean followLinks;

        // set to true when binding to another object
        volatile boolean forwarding;

        BasicForwardingFileAttributeView(UnixPath file,
                                         BasicFileAttributeView forwardee,
                                         boolean followLinks)
        {
            this.file = file;
            this.forwardee = forwardee;
            this.followLinks = followLinks;
            this.forwarding = false;
        }

        int open() throws IOException {
            int oflags = O_RDONLY;
            if (!followLinks)
                oflags |= O_NOFOLLOW;
            try {
                return openat(dfd, file.asByteArray(), oflags, 0);
            } catch (UnixException x) {
                x.rethrowAsIOException(file);
                return -1; // keep compiler happy
            }
        }

        private void checkWriteAccess() {
            SecurityManager sm = System.getSecurityManager();
            if (sm != null) {
                ds.directory().resolve(file).checkWrite();
            }
        }

        @Override
        public BasicFileAttributeView bind(FileRef obj) {
            return bind(obj, true);
        }

        @Override
        public BasicFileAttributeView bind(FileRef obj, boolean followLinks) {
            forwardee.bind(obj, followLinks);
            forwarding = true;
            return this;
        }

        @Override
        public BasicFileAttributes readAttributes() throws IOException {
            if (forwarding)
                return forwardee.readAttributes();

            ds.readLock().lock();
            try {
                if (!ds.isOpen())
                    throw new ClosedDirectoryStreamException();

                SecurityManager sm = System.getSecurityManager();
                if (sm != null) {
                    if (file == null) {
                        ds.directory().checkRead();
                    } else {
                        ds.directory().resolve(file).checkRead();
                    }
                }
                try {
                     UnixFileAttributes attrs = (file == null) ?
                         UnixFileAttributes.get(dfd) :
                         UnixFileAttributes.get(dfd, file.asByteArray(), followLinks);

                     // SECURITY: must return as BasicFileAttribute
                     return attrs.asBasicFileAttributes();
                } catch (UnixException x) {
                    x.rethrowAsIOException(file);
                    return null;    // keep compiler happy
                }
            } finally {
                ds.readLock().unlock();
            }
        }


        @Override
        public BasicFileAttributeView setTimes(Long lastModifiedTime,
                                               Long lastAccessTime,
                                               Long createTime, // ignore
                                               TimeUnit unit)
            throws IOException
        {
            if (forwarding) {
                forwardee.setTimes(lastModifiedTime, lastAccessTime, createTime, unit);
                return this;
            }

            // no effect
            if (lastModifiedTime == null && lastAccessTime == null) {
                return this;
            }

            checkWriteAccess();

            ds.readLock().lock();
            try {
                if (!ds.isOpen())
                    throw new ClosedDirectoryStreamException();

                int fd = (file == null) ? dfd : open();
                try {
                    UnixFileAttributes attrs = null;

                    // if not changing both attributes then need existing attributes
                    if (lastModifiedTime == null || lastAccessTime == null) {
                        try {
                            attrs = UnixFileAttributes.get(fd);
                        } catch (UnixException x) {
                            x.rethrowAsIOException(file);
                        }
                    }

                    // modified time = existing, now, or new value
                    long modTime;
                    if (lastModifiedTime == null) {
                        modTime = attrs.lastModifiedTime();
                    } else {
                        if (lastModifiedTime >= 0L) {
                            modTime = TimeUnit.MILLISECONDS.convert(lastModifiedTime, unit);
                        } else {
                            if (lastModifiedTime != -1L)
                                throw new IllegalArgumentException();
                            modTime = System.currentTimeMillis();
                        }
                    }

                    // access time = existing, now, or new value
                    long accTime;
                    if (lastAccessTime == null) {
                        accTime = attrs.lastAccessTime();
                    } else {
                        if (lastAccessTime >= 0L) {
                            accTime = TimeUnit.MILLISECONDS.convert(lastAccessTime, unit);
                        } else {
                            if (lastAccessTime != -1L)
                                throw new IllegalArgumentException();
                            accTime = System.currentTimeMillis();
                        }
                    }

                    try {
                        futimes(fd, accTime, modTime);
                    } catch (UnixException x) {
                        x.rethrowAsIOException(file);
                    }
                } finally {
                    if (file != null)
                        UnixNativeDispatcher.close(fd);
                }
            } finally {
                ds.readLock().unlock();
            }
            return this;
        }
    }

    /**
     * PosixFileAttributeView that works initially on the dfd/name pair. When
     * the bind method is used to bind the view to a another file then it
     * forwards.
     */
    private class PosixForwardingFileAttributeView
        extends BasicForwardingFileAttributeView implements PosixFileAttributeView
    {
        PosixForwardingFileAttributeView(UnixPath file,
                                         PosixFileAttributeView forwardee,
                                         boolean followLinks)
        {
            super(file, forwardee, followLinks);
        }

        private void checkWriteAndUserAccess() {
            SecurityManager sm = System.getSecurityManager();
            if (sm != null) {
                super.checkWriteAccess();
                sm.checkPermission(new RuntimePermission("accessUserInformation"));
            }
        }

        @Override
        public PosixFileAttributeView bind(FileRef obj) {
            super.bind(obj);
            return this;
        }

        @Override
        public PosixFileAttributeView bind(FileRef obj, boolean followLinks) {
            super.bind(obj, followLinks);
            return this;
        }

        @Override
        public PosixFileAttributes readAttributes() throws IOException {
            if (forwarding)
                return (PosixFileAttributes)forwardee.readAttributes();

            SecurityManager sm = System.getSecurityManager();
            if (sm != null) {
                if (file == null)
                    ds.directory().checkRead();
                else
                    ds.directory().resolve(file).checkRead();
                sm.checkPermission(new RuntimePermission("accessUserInformation"));
            }

            ds.readLock().lock();
            try {
                if (!ds.isOpen())
                    throw new ClosedDirectoryStreamException();

                try {
                     UnixFileAttributes attrs = (file == null) ?
                         UnixFileAttributes.get(dfd) :
                         UnixFileAttributes.get(dfd, file.asByteArray(), followLinks);
                     return attrs;
                } catch (UnixException x) {
                    x.rethrowAsIOException(file);
                    return null;    // keep compiler happy
                }
            } finally {
                ds.readLock().unlock();
            }
        }

        @Override
        public Attribute<Set<PosixFilePermission>> newPermissionsAttribute() {
            // always forward
            return ((PosixFileAttributeView)forwardee).newPermissionsAttribute();
        }

        @Override
        public PosixFileAttributeView setTimes(Long lastModifiedTime,
                                               Long lastAccessTime,
                                               Long createTime, // ignore
                                               TimeUnit unit)
            throws IOException
        {
            super.setTimes(lastModifiedTime, lastAccessTime, createTime, unit);
            return this;
        }


        @Override
        public PosixFileAttributeView setPermissions(Set<PosixFilePermission> perms)
            throws IOException
        {
            if (forwarding) {
                ((PosixFileAttributeView)forwardee).setPermissions(perms);
                return this;
            }

            // permission check
            checkWriteAndUserAccess();

            ds.readLock().lock();
            try {
                if (!ds.isOpen())
                    throw new ClosedDirectoryStreamException();

                int fd = (file == null) ? dfd : open();
                try {
                    fchmod(fd, UnixFileModeAttribute.toUnixMode(perms));
                } catch (UnixException x) {
                    x.rethrowAsIOException(file);
                } finally {
                    if (file != null && fd >= 0)
                        UnixNativeDispatcher.close(fd);
                }
            } finally {
                ds.readLock().unlock();
            }

            return this;
        }

        private void setOwners(int uid, int gid) throws IOException {
            // permission check
            checkWriteAndUserAccess();

            ds.readLock().lock();
            try {
                if (!ds.isOpen())
                    throw new ClosedDirectoryStreamException();

                int fd = (file == null) ? dfd : open();
                try {
                    fchown(fd, uid, gid);
                } catch (UnixException x) {
                    x.rethrowAsIOException(file);
                } finally {
                    if (file != null && fd >= 0)
                        UnixNativeDispatcher.close(fd);
                }
            } finally {
                ds.readLock().unlock();
            }
        }

        @Override
        public PosixFileAttributeView setOwner(UserPrincipal owner)
            throws IOException
        {
            if (forwarding) {
                ((PosixFileAttributeView)forwardee).setOwner(owner);
                return this;
            }
            if (owner.isGroup())
                throw new IllegalArgumentException("Owner parameter can't be group");
            if (!(owner instanceof UnixUserPrincipal))
                throw new ProviderMismatchException();
            int uid = ((UnixUserPrincipal)owner).uid();
            setOwners(uid, -1);
            return this;
        }

        @Override
        public PosixFileAttributeView setGroup(UserPrincipal group)
            throws IOException
        {
            if (forwarding) {
                ((PosixFileAttributeView)forwardee).setGroup(group);
                return this;
            }
            if (!group.isGroup())
                throw new IllegalArgumentException("Group parameter must be a group");
            if (!(group instanceof UnixUserPrincipal))
                throw new ProviderMismatchException();
            int gid = ((UnixUserPrincipal)group).gid();
            setOwners(-1, gid);
            return this;
        }

        @Override
        public UserPrincipal lookupPrincipalByName(String name)
            throws IOException
        {
            // always forward
            return ((PosixFileAttributeView)forwardee).lookupPrincipalByGroupName(name);
        }

        @Override
        public UserPrincipal lookupPrincipalByGroupName(String group)
            throws IOException
        {
            // always forward
            return ((PosixFileAttributeView)forwardee).lookupPrincipalByGroupName(group);
        }
    }
}
